/**
 *  Copyright 2011 Marco Berri - marcoberri@gmail.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 **/
package com.stats.view;

import com.Base;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.utils.StringUtil;

/**
 *
 * @author Marco Berri marcoberri@gmail.com
 */
public class One extends com.stats.Base {

    /**
     * Url
     */
    protected String url;
    /**
     *
     */
    protected String url_originale;
    /**
     *
     */
    protected String charset = "UTF-8";

    /** 
     * 
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        super.processRequest(request,response);

        if (isIpNullOrSpam(request.getRemoteAddr())) {
            return;
        }

        //prelevo i parametri in arrivo che devono essere 1... per ora...
        url_originale = url = request.getParameter("url");

        if (StringUtil.isNullOrEmpty(url)) {
            fatal("Url non valida (1) :" + url);
            return;
        }


        url = url.replaceAll("/r/", "");

        if (StringUtil.isNullOrEmpty(url)) {
            fatal("Url non valida (2) :" + url);
            return;
        }

        ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
        try {
            Statement stat = this.conn_stats.createStatement();
            ResultSet rs = stat.executeQuery("select * from view where fk_url_id ='" + url + "' order by ts desc");



            while (rs.next()) {
                HashMap<String, Object> m = new HashMap<String, Object>();
                String ip = rs.getString("ip");
                m.put("ts", rs.getString("ts"));
                m.put("ip", ip);


                if (!StringUtil.isNullOrEmpty(rs.getString("header"))) {
                    HashMap<String, String> header_map = new HashMap<String, String>();
                    String[] h_string = rs.getString("header").split("\\|\\|");
                    for (String s : h_string) {
                        try {
                            if (!isValidHeaderKey(s.split("\\|")[0])) {
                                continue;
                            }

                            header_map.put(s.split("\\|")[0], s.split("\\|")[1]);
                        } catch (Exception e2) {
                            continue;
                        }
                    }

                    m.put("header", header_map);
                }

                list.add(m);
            }

            rs.close();

        } catch (SQLException ex) {
            fatal("SQLException", ex);
        }


        response.setContentType("text/html;charset=" + this.charset);


        PrintWriter out = response.getWriter();
        HashMap<String, Object> m = new HashMap<String, Object>();
        m.put("charset", this.charset);
        m.put("stats", list);
        m.put("url_originale", url_originale);

        m.put("tot_view", tot_view);
        m.put("tot_save", tot_save);
        m.put("tot_ts", tot_ts);


        out.println(velocity.render("template/stats/one.vtl", m));
        out.close();


    }

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Statistiche di click sul singolo short url";
    }// </editor-fold>

    /**
     *
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

    }

    /**
     * Destroy
     */
    @Override
    public void destroy() {
        super.destroy();
    }
}
